<?php
/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/4/2
 * Time: 13:49
 */

namespace app\api\service;

use app\admin\model\MinerPool as MinerPoolModel;
use app\api\model\Images;
use app\facade\Basic;
use think\facade\Db;

class MinerPool
{

    protected $model;

    public function __construct()
    {
        $this->model = new MinerPoolModel();

    }

    /**
     * @describe 获取矿池列表
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList($params): array
    {
        #验证参数
        if (!isset($params['currency_ids']) || !$params['currency_ids']) {
            return Basic::data( 100002, 'common.parameterError');
        }
        #处理查询条件
        $where = ['is_del' => 0];
        $ids = Db::name('miner_pool_support_currency')->whereIn('currency_id',$params['currency_ids'])->where($where)->column('miner_pool_id');
        $ids = array_unique($ids);
        if(empty($ids)){
            return Basic::data( 0, 'common.success', []);
        }
        $sql = $this->model->where($where)->whereIn('id',$ids);
        #取数据
        $list = $sql->field('name,image,link')->select()->toArray();
        if (!$list) {
            return Basic::data(0, 'common.success', []);
        }
        $photoId = array_unique(array_column($list,'image'));
        #获取图片url
        $oImages = new Images();
        $photoUrls = $oImages->getImagesByIds($photoId);
        $avatorUrls = array_column($photoUrls, null, 'id');
        #替换url
        foreach ($list as $k=>$v){
            $list[$k]['image'] = $avatorUrls[$v['image']]['url']??'';
        }
        return Basic::data(0, 'common.success',  $list);
    }

    public function getListBySku($params): array
    {
        # 验证参数
        if (!isset($params['sku_id']) || !$params['sku_id']) {
            return Basic::data(100002, 'common.parameterError');
        }

        # 处理查询条件
        $where = ['is_del' => 0];

        // 获取算法类型
        $algorithm = Db::name('product')->where($where)->where('id', $params['sku_id'])->value('algorithm');
        if (!$algorithm) {
            return Basic::data(0, 'common.success', []);
        }
        $algorithm = explode(',',$algorithm);
        // 获取匹配算法的币种列表
        $currencies = Db::name('product_currency')
            ->where($where)
            ->where('if_show',1)
            ->whereIn('algorithm', $algorithm)
            ->field('id')
            ->select()
            ->toArray();

        if (!$currencies) {
            return Basic::data(0, 'common.success', []);
        }

        $currency_ids = array_column($currencies, 'id');

        // 获取矿池支持币种信息
        $supportData = Db::name('miner_pool_support_currency')
            ->whereIn('currency_id', $currency_ids)
            ->where($where)
            ->field('miner_pool_id, currency_id, rating')
            ->select()
            ->toArray();

        if (empty($supportData)) {
            return Basic::data(0, 'common.success', []);
        }

        // 获取币种图片信息 - 修复：确保直接获取图片地址字符串
        // 修改前：->column('id, image', 'id')
        // 修改后：->column('image', 'id')
        $currency_info = Db::name('product_currency')
            ->where($where)
            ->whereIn('id', $currency_ids)
            ->column('image', 'id');

        // 按矿池分组币种信息
        $pool_currencies = [];
        foreach ($supportData as $item) {
            $poolId = $item['miner_pool_id'];
            $currencyId = $item['currency_id'];

            // 处理可能为null的rating字段
            $ratingJson = $item['rating'] ?: '{}';
            $rating = json_decode($ratingJson, true) ?: [];

            $processedRate = [];
            if (!empty($rating)) {
                // 处理费率信息
                foreach ($rating['selectedRates'] ?? [] as $rateType) {
                    $processedRate[$rateType] = (isset($rating['rates'][$rateType]) && $rating['rates'][$rateType]) ? $rating['rates'][$rateType].'%' : '';
                }
            }

            // 修复：直接使用图片地址字符串
            $pool_currencies[$poolId][] = [
                'image' => $currency_info[$currencyId] ?? '', // 直接是字符串
                'rate' => $processedRate,
                'id' =>$currencyId
            ];
        }

        // 获取矿池ID列表
        $pool_ids = array_unique(array_column($supportData, 'miner_pool_id'));

        // 获取矿池基本信息
        $pools = $this->model->where($where)
            ->whereIn('id', $pool_ids)
            ->field('id, name, image, link')
            ->select()
            ->toArray();

        if (!$pools) {
            return Basic::data(0, 'common.success', []);
        }

        // 处理矿池图片
        $photoIds = array_filter(array_unique(array_column($pools, 'image')));
        $avatarUrls = [];

        if (!empty($photoIds)) {
            $oImages = new Images();
            $photoUrls = $oImages->getImagesByIds($photoIds);
            $avatarUrls = array_column($photoUrls, 'url', 'id'); // 优化：直接创建 url=>id 映射
        }

        // 构建返回数据结构
        foreach ($pools as &$pool) {
            // 设置矿池图片URL
            $pool['image'] = $avatarUrls[$pool['image']] ?? '';

            // 添加币种信息
            $pool['coin'] = $pool_currencies[$pool['id']] ?? [];

            // 移除ID字段
            unset($pool['id']);
        }

        return Basic::data(0, 'common.success', $pools);
    }
}